﻿using cyq_dnetmvc.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;

namespace cyq_dnetmvc.Controllers
{
    public class CwCController : BaseController
    {
        //
        // GET: /CwC/

        public ActionResult Index()
        {
            List<topictable> topicList = (from m in db.topictable
                                          orderby m.topic_priority descending, m.topic_createtime descending
                                          select m).ToList();

            ViewBag.version = staticversion;
            return View(topicList);
        }
        public ActionResult ChatRoom(int id = 0)
        {
            List<chattable> chatList = (from m in db.chattable
                                        where m.chat_topicid == id
                                        orderby m.chat_createtime ascending
                                        select m).ToList();

            ViewBag.version = staticversion;
            //就一个id没必要再建model
            ViewBag.chatroomid = id;
            return View("ChatRoom_binddata", chatList);
        }
        [HttpPost]
        public ActionResult AddOneCell(int topicid, string content, int celltype, int cellbg1, int? cellbg2, int dialogtype)
        {
            if (content.Length <= 75)
            {
                #region 存储
                chattable achat = new chattable();

                achat.chat_topicid = topicid;
                achat.chat_content = content;
                achat.chat_celltype = celltype;
                achat.chat_cell1bg = cellbg1;
                achat.chat_cell2bg = cellbg2;
                achat.chat_dialogtype = dialogtype;
                achat.chat_userip = GetRealIp();

                db.chattable.AddObject(achat);


                try
                {
                    db.SaveChanges();
                    var jsonresult = new
                    {
                        resultcode = 1,
                        msg = "又多了一格~",
                        dialog = new { 
                            chat_id=achat.chat_id,
                            chat_content=achat.chat_content,
                            chat_celltype=achat.chat_celltype,
                            chat_cell1bg=achat.chat_cell1bg,
                            chat_cell2bg=achat.chat_cell2bg,
                            chat_dialogtype=achat.chat_dialogtype
                        }
                    };
                    return Json(jsonresult, JsonRequestBehavior.AllowGet);
                }
                catch
                {
                    var jsonresult = new
                    {
                        resultcode = 0,
                        msg = "偶真的没有审核，是服务器傲娇的拒绝了你",
                    };
                    return Json(jsonresult, JsonRequestBehavior.AllowGet);
                }
                #endregion
            }
            else
            {
                var jsonresult = new
                {
                    resultcode = 0,
                    msg = "耍小诡计是不行的哟",
                };
                return Json(jsonresult, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 获取ip 此类私有方法暂时
        /// </summary>
        /// <returns></returns>
        private string GetRealIp() {
            string result = String.Empty;
            result = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDE"];

            if (!string.IsNullOrWhiteSpace(result)) {
                if (-1 == result.IndexOf("."))
                {
                    result = null;
                }
                else {
                    if (-1 != result.IndexOf(",")) { 
                        //多个
                        result = result.Replace(" ", string.Empty).Replace("\"", string.Empty);
                        string[] temporaryips = result.Split(",;".ToCharArray());
                        if (temporaryips != null && temporaryips.Length > 0) {
                            for (int i = 0; i < temporaryips.Length; i++) {
                                //不是内网ip
                                if (IsIPAddress(temporaryips[i]) 
                                    && temporaryips[i].Substring(0, 3) != "10."
                                    && temporaryips[i].Substring(0, 7) != "192.168"
                                    && temporaryips[i].Substring(0, 7) != "172.16.") {
                                    //这样大概返回的是第一个匹配的
                                    return temporaryips[i];
                                }
                            }
                        }
                    }
                    else if (IsIPAddress(result))
                    {
                        return result;
                    }
                    else {
                        result = null;
                    }
                }
            }
            if (string.IsNullOrWhiteSpace(result)) {
                result = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }
            if (string.IsNullOrWhiteSpace(result)) {
                result = System.Web.HttpContext.Current.Request.UserHostAddress;
            }
            return result;
        }
        /// <summary>
        /// 判断是否是ip地址格式
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private bool IsIPAddress(string str) {
            if (string.IsNullOrWhiteSpace(str) || str.Length < 7 || str.Length > 15)
                return false;

            string regformat = @"^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})";
            Regex regex = new Regex(regformat,RegexOptions.IgnoreCase);
            return regex.IsMatch(str);
        }
    }
}
